package kr.hkit.androidcomplete03.ch29;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import kr.hkit.androidcomplete03.R;
import kr.hkit.androidcomplete03.ch29.common.Item;
import kr.hkit.androidcomplete03.ch29.common.MyAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;

public class JsonParser extends Activity {
	ListView list;
	ProgressDialog progressDlg;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.parser);
		list = (ListView) findViewById(R.id.orderlistview);
		new ParsingXml().execute("order.json");
	}

	private class ParsingXml extends AsyncTask<String, Void, ArrayList<Item>> {

		@Override
		protected void onPreExecute() {
			progressDlg = ProgressDialog.show(JsonParser.this, "Wait",
					"order.xml & order.json Making ...");
		}

		@Override
		protected void onPostExecute(ArrayList<Item> result) {
			MyAdapter adapter = new MyAdapter(JsonParser.this, result);
			progressDlg.dismiss();
			list.setAdapter(adapter);
		}

		@Override
		protected ArrayList<Item> doInBackground(String... params) {
			StringBuffer sb = new StringBuffer();
			String str = null;
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(
						openFileInput(params[0])));
				while ((str = br.readLine()) != null) {
					sb.append(str);
				}
				br.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return parsingXml(sb.toString());
		}

		private ArrayList<Item> parsingXml(String xml) {
			ArrayList<Item> arList = new ArrayList<Item>();
			Item item = null;
			try {
				JSONArray ja = new JSONArray(xml);
				for(int i = 0; i < ja.length(); i++){
					JSONObject jsonobj = ja.getJSONObject(i);
					item = new Item();
					item.setItemName(jsonobj.getString("Product"));
					item.setItemMaker(jsonobj.getString("Maker"));
					item.setItemPrice(jsonobj.getInt("Price"));
					arList.add(item);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			

			return arList;
		}

	}
}
